package giab.weixin.web.util;



import java.lang.reflect.Field;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.tree.DefaultElement;
import org.springframework.stereotype.Component;


@Component
public class XmlUtil {

	public String objectToXml(Object object) {
		StringBuffer xmlBuffer = new StringBuffer();
		xmlBuffer.append("<xml>");
		Field[] properties = object.getClass().getDeclaredFields();
		for (Field field : properties) {
			field.setAccessible(true);
			if (field.getName().equals("CreateTime")||field.getName().equals("MsgId")) {
				xmlBuffer.append("<" + field.getName() + ">"
						+ getObjectToString(field, object) + "</"
						+ field.getName() + ">");
			}
			else {
				xmlBuffer.append("<" + field.getName() + "><![CDATA["+ getObjectToString(field, object) + "]]></"+ field.getName() + ">");
			}
		}
		xmlBuffer.append("</xml>");
		return xmlBuffer.toString();
	}

	public Object xmlToObject(String xml, Class cls) {
		Document doc = null;
		try {			
			doc = DocumentHelper.parseText(xml);
//			System.err.println(doc.getText());
			Object obj = cls.newInstance();
			Field[] fields = obj.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				Object el = doc.selectObject("//"+field.getName());
				if(el!=null){
					field.set(obj, ((DefaultElement)el).getText().replace(Constant.XML_TO_STRING_REPLACE_PREFIX, "").replace(Constant.XML_TO_STRING_REPLACE_SUFFIX, ""));	
				}				
			}
			return obj;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return null;
	}
	
	public String xmlToString(){
		Document doc = null;		
		return "";
	}

	private String getObjectToString(Field field, Object obj) {
		try {
			return field.get(obj).toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "";
		}
	}

	/*public static void main(String[] args) {
//		WeixinLogin login = new WeixinLogin();
//		login.setEchostr("echoss");
//		login.setNonce("111");
//		login.setSignature("de");
//		login.setTimestamp(System.currentTimeMillis() + "");
//		String xdml = new XmlUtil().objectToXml(login);
		String xml ="<xml><signature>de</signature><timestamp>1366009852233</timestamp><nonce>无错</nonce><echostr>echoss</echostr></xml>";
		Object object =new XmlUtil().xmlToObject(xml, WeixinLogin.class);
		if(object!=null){
			WeixinLogin lo = (WeixinLogin)object;
			System.err.println(lo.getTimestamp());
		}
	}*/

}
